import math

import sqlalchemy
from flask import render_template, url_for
from flask_login import logout_user, current_user
from sqlalchemy.orm import scoped_session, sessionmaker

from WEB.app.Decorator.Login import pc_admin_login_required
from WEB.app.app import db, app
from WEB.app.forms.admin.uoload import get_admin_upload_txt_form
from WEB.app.models import AdminImportEmail, UploadLog, User


@pc_admin_login_required
def index():
    form = get_admin_upload_txt_form()

    class EmailData():
        total = 0
        not_used_total = 0
        used_total = 0

    email_data = EmailData()

    email = AdminImportEmail()
    email_data.total = email.query.count()
    email_data.not_used_total = email.query.filter(AdminImportEmail.is_used == 0).count()
    email_data.used_total = email.query.filter(AdminImportEmail.is_used == 1).count()
    email_data.distribute_url = url_for('admin_distribute_email')

    class Operator:
        total = 0
        users = None

    operator = Operator()
    operator.total = User.query.count()
    operator.users = User.query.all()
    operator.send_total = email.query.filter(AdminImportEmail.is_send == 1).count()
    operator.wait_send_total = email.query.filter(AdminImportEmail.is_send == 0).count()

    for user in operator.users:
        user.send_total = email.query.filter(AdminImportEmail.used_user_id == user.id,
                                             AdminImportEmail.is_send == 1).count()
        user.wait_send_total = email.query.filter(AdminImportEmail.used_user_id == user.id,
                                                  AdminImportEmail.is_send == 0).count()

    upload_log = UploadLog()
    upload_logs = upload_log.query.order_by(db.desc(UploadLog.create_time)).limit(3).all()
    print('账户')
    print(current_user.name)
    return render_template('admin/index.html', form=form, email_data=email_data, operator=operator,
                           upload_log=upload_logs)


@pc_admin_login_required
def admin_distribute_email():
    email = AdminImportEmail()
    emails = email.query.filter(AdminImportEmail.is_used == 0)
    email_total = emails.count()

    users = User.query.filter(User.active == 1)
    users_total = users.count()
    all_users = users.all()
    print('用户')
    print(all_users)

    class CutData():
        user_id = None
        emails = None

    cut_result = []
    n = len(all_users)
    for i in range(n):
        user = all_users[i]
        per_list = emails[math.floor(i / n * email_total):math.floor((i + 1) / n * email_total)]
        cut_data = CutData()
        cut_data.user_id = user.get_id()
        cut_data.emails = per_list
        cut_result.append(cut_data)
    connection = db.session.connection()

    table = AdminImportEmail.__tablename__
    for user_data in cut_result:
        user_id = user_data.user_id
        email_ids = []
        for email in user_data.emails:
            email_ids.append(str(email.id))
        ids = ','.join(email_ids)
        if ids:
            connection.execute(
                'UPDATE `' + table + '` SET `is_used`=1,`used_user_id`="' + str(user_id) + '" WHERE id IN(' + ids + ')')
        else:
            pass
    db.session.commit()
    return render_template('admin/common/tool/msg.html',
                           msg='邮件分配完毕！一共分配了：' + str(email_total) + '个邮件' + ' 分配 ' + str(n) + ' 个用户',
                           url=url_for('admin'))


@pc_admin_login_required
def logout():
    logout_user()
    return render_template('admin/common/tool/msg.html', msg='退出成功！', time=2, url=url_for('admin_login'))
